package appnode;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import appnode.Node;
import appnode.PMF;

public class Addnode extends HttpServlet {

	
		private static final Logger log = Logger.getLogger(Addnode.class.getName());

	    public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {
			UserService userService = UserServiceFactory.getUserService();
	        User user = userService.getCurrentUser();
			String owner = user.getNickname();
			String nodename = req.getParameter("nodename");
			String lat = req.getParameter("lat");
			String lng = req.getParameter("lng");
			
			//chek the nodename
			PersistenceManager pm = PMF.get().getPersistenceManager();
			String query = "select from " + Node.class.getName() + " where nodename==" + "'" + nodename + "'";
		    List<Node> results = (List<Node>) pm.newQuery(query).execute();
			if (results.isEmpty()){
				Node n = new Node(owner,nodename,lat,lng,new Date());
				try{
					pm.makePersistent(n);
				} finally {
					pm.close();
				}
				resp.setContentType("text/html");
				resp.getWriter().print("<html>");
				resp.getWriter().print("You add new node succesfully");
				resp.getWriter().print("<br>");
				resp.getWriter().print("<a href='map?nodename="+ nodename + "'>See</a> the node on the map");
				resp.getWriter().print("</html>");
				resp.sendRedirect("/map?nodename="+nodename);
			
			}	
				else {
					resp.setContentType("text/html");
					resp.getWriter().print("<html>");
					resp.getWriter().print("The node already exists!");
					resp.getWriter().print("<br>");
					resp.getWriter().print("<a href='/addnewnode.jsp'>Add</a> node again ");
					resp.getWriter().print("</html>");
				}
		}
}